# Copyright (c) 2005,2006,2007 Dynamic Solutions Inc. (support@dynamic-solutions.com)
#
# This file is part of DataZoomer.
#
# DataZoomer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# DataZoomer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Generate HTML"""


# Create an empty dictionary that is used for substitution in hReplaceTags
import sys
from dzutil import url_for, link_to
from dzmodel import RecordIterator

dic = {}


def hTest():
    print 'Test complete'

def hReplaceTags(aPage,dic1=0):
    import string
    p1 = string.find(aPage,'<#')
    crazyloop=0
    while p1 > -1 and crazyloop<100:
        crazyloop = crazyloop + 1
        restofpage = aPage[p1+2:]
        p2 = string.find(restofpage,'>')
        if p2 > 0:
            expr = restofpage[:p2]
            if dic.has_key(expr):
                try:
                    repl = dic[expr] + ''
                except:
                    repl = expr + '=Invalid Expression'
            else:
                repl = '{'+expr+'}'
            aPage = string.replace(aPage,'<#'+expr+'>',repl)
        else:
            return 'Nesting error in aPage'
        p1 = string.find(aPage,'<#')
    return aPage

def hMessageBox(title,contents):
    return '<table border=1 width=100% bordercolor=#666666 cellpadding=0 cellspacing=0>'+\
           '<tr><td valign=top bgcolor=#CCCCCC><font name="Fixed" size=-1 color=#000000>&nbsp;<b>'+title+'</b></font></td></tr>'+\
           '<tr><td valign=top ><table width=100% cellpadding=3 cellspacing=0 bgcolor=#EEEEEE><tr><td valign=top bgcolor=#FFFFFF>'+contents+'</td></tr></table></td></tr>'+\
           '</table><br>'

def hMessageBox2(title,contents):
    return '<table width=100% bordercolor=#666666 border=1 cellpadding=0 cellspacing=0>'+\
           '<tr><td valign=top bgcolor=#EEEEEE><font size=-2 color=#000000><strong>&nbsp;'+title+'</strong></font></td></tr>'+\
           '<tr><td valign=top ><table width=100% cellpadding=3 cellspacing=0 bgcolor=#EEEEEE><tr><td valign=top bgcolor=#FFFFFF>'+contents+'</td></tr></table></td></tr>'+\
           '</table><BR>'

def hPanelBoxOld(title,contents):
    return '<table border=1 width=100% bordercolor=#666666 cellpadding=0 cellspacing=0>'+\
           '<tr><td valign=top bgcolor=#CCCCCC><font size=-2 color=#000000><strong>&nbsp;'+title+'</strong></font></td></tr>'+\
           '<tr><td valign=top ><table width=100% cellpadding=3 cellspacing=0 bgcolor=#EEEEEE><tr><td valign=top bgcolor=#FFFFFF>'+contents+'</td></tr></table></td></tr>'+\
           '</table><BR>'

def hPanelBox(title,contents):
    panel = TWebPage()
    panel.BOXTITLE = title
    panel.BOXCONTENTS = contents
    tpl = hTemplate('panelbox.htm')
    return hFill(tpl,panel)

def hTableRowTemplate(fieldArray):
    r = ''
    for field in fieldArray:
        r = r + '<td valign=top><#' + field + '></td>'
    return r

def hTableRowHeader(fieldArray):
    r = ''
    for field in fieldArray:
        r = r + '<td valign=top>' + field + '</td>'
    return r

def hTable(dataset,tableTemplate='!',rowTemplate='!'):
    if tableTemplate=='!':
        tableTempalte = '<table class=body width=100% border=1 bordercolor=#00AA00 cellpadding=0 cellspacing=2><#ROWS></table>'
    if rowTemplate=='!':
        rowTemplate = hTableRowTemplate(dataset.fields)
    r = '<table><tr>'
    for field in dataset.fieldnames:
        r = r + '<th>' + field + '<hr></th>'
    r = r + '</tr>'
    for row in dataset.data:
        r = r + '<tr>'
        for col in row:
            r = r + '<td>' + col + '</td>'
        r = r + '</tr>'
    return r  + '</table>'

def hInclude(filename):
    f = open(filename,'r')
    return f.read()

def hShowPage(filename):
    t = hInclude(filename)
    return hReplaceTags(t)

def hTemplate(file):
    try:
      try:
          return hInclude(tpl_path+file+'.htm')
      except:
          return hInclude(tpl_path+file)
    except:
      try:
          return hInclude(stpl_path+file+'.htm')
      except:
          return hInclude(stpl_path+file)

def hPage(aPage):
    dic['PAGETITLE'] = aPage.PAGETITLE
    dic['PAGECONTENT'] = aPage.PAGECONTENT
    return hResult()

def hFeedbackPanel():
    return hMessageBox('Feedback',hTemplate('feedback.htm'))

def hResult():
    return hShowPage(tpl_path+'page.htm')

def hSimpleForm(script,fields):
    return '<form method=POST action='+script+'>\n'+\
           fields+'\n'+\
           '</form>'

def hFormatPage(left,middle,right=''):
    t = '<table width=100% cellpadding=0 cellspacing=0 height=400><tr>'+\
        '<td width=5 valign=top><img src=/images/spacer.gif height=1 width=5></td>' + \
        '<td width=150  valign=top><img src=/images/spacer.gif height=1 width=150>'+left+'</td>' + \
        '<td width=5 valign=top><img src=/images/spacer.gif height=1 width=5></td>' + \
        '<td width=100% valign=top><img src=/images/spacer.gif height=1 width=150>'+middle+'</td>' + \
        '<td width=5 valign=top><img src=/images/spacer.gif height=1 width=5></td>' + \
        '<td width=150  valign=top><img src=/images/spacer.gif height=1 width=150>'+right+'</td>' + \
        '<td width=5 valign=top><img src=/images/spacer.gif height=1 width=5></td>' + \
        '</tr></table>'
    return t

def hFormat(obj,aTemplate):
    return hFill(aTemplate,obj)

def hFill(aPage,obj):
    import string
    start_com = '<!--'
    end_com   = '-->'

    start_com_len = len(start_com)

    result = ''
    restofpage = aPage
    p1 = restofpage.find(start_com)
    crazyloop=0
    while p1 > -1 and crazyloop<100 and restofpage:
        crazyloop = crazyloop + 1
        html_section = restofpage[:p1]

        p2 = string.find(restofpage[p1:],end_com)

        if p2 != -1:
            comment_section = restofpage[p1:][:p2+start_com_len-1]
            restofpage = restofpage[p1:][p2+start_com_len-1:]
        else:
            # This may indicate an error
            comment_section = restofpage[p1:][p2+start_com_len:]
            restofpage = ''

        tt = comment_section.replace('<','&lt;').replace('\n','')

        result += hFillSection(html_section,obj) + comment_section
        p1 = string.find(restofpage,start_com)

    return result + hFillSection(restofpage,obj)


def hFillSection(aPage,obj):
    import string

    start_tag = '<#'
    end_tag   = '>'
    start_tag_len = len(start_tag)

    p1 = string.find(aPage,start_tag)
    crazyloop=0
    d = obj.__dict__
    while p1 > -1 and crazyloop<100:
        crazyloop = crazyloop + 1
        restofpage = aPage[p1+start_tag_len:]
        p2 = string.find(restofpage,end_tag)
        if p2 > 0:
            expr = restofpage[:p2]
            repl = hReplaceTag(expr,obj)
            aPage = string.replace(aPage,start_tag+expr+end_tag,repl)
        else:
            return 'Nesting error in aPage'
        p1 = string.find(aPage,start_tag)
    return aPage

def ohFill(aPage,obj):
    import string
    start_tag = '{'
    end_tag   = '}'
    start_tag_len = len(start_tag)

    p1 = string.find(aPage,start_tag)
    crazyloop=0
    d = obj.__dict__
    while p1 > -1 and crazyloop<100:
        crazyloop = crazyloop + 1
        restofpage = aPage[p1+start_tag_len:]
        p2 = string.find(restofpage,end_tag)
        if p2 > 0:
            expr = restofpage[:p2]
            repl = hReplaceTag(expr,obj)
            aPage = string.replace(aPage,start_tag+expr+end_tag,repl)
        else:
            return 'Nesting error in aPage'
        p1 = string.find(aPage,start_tag)
    return aPage

def x_hReplaceTag(expr,obj):
    tag  = expr.split(' ')[0].upper()
    rest = expr.split(' ')[1:]

    options = {}
    for item in rest:
        opt = item.split('=')
        options[opt[0].lower()] = opt[1]

    if obj.__dict__.has_key(tag):
        if tag=='sid':
            repl = 'test<br>' + tag + '<br>' + obj.__dict__['sid'] + '<br>' + obj.__dict__[tag]
        else:
            try:
                repl = obj.__dict__[tag] + ''
            except:
                try:
                    repl = repr(obj.__dict__[tag])
                except:
                    repl = 'Invalid expression:' + tag + repr(obj.__dict__)
    elif tag == 'DEBUG':
        return ''
    else:
        repl = '[' + expr + ']'

    return hFill(repl,obj)

def hReplaceTag(expr,obj):
    tag  = expr.split(' ')[0].upper()
    rest = expr.split(' ')[1:]

    options = {}
    for item in rest:
        opt = item.split('=')
        options[opt[0].lower()] = opt[1]

    try:
        repl = '%s' % obj.__dict__[tag]
    except:
        try:
            try:
                repl = '%s' % obj.__getattr__(tag)
            except:
                repl = '%s' % obj.replace_tag(tag,options)
        except:
            raise
#            repl = '[%s]' % tag

    return hFill(repl,obj)

class TWebContent:
    def __init__(self,template):
        self.tpl = template
    def render(self,template=''):
        return hFill(self.tpl,self)

class TWebPage:
    def __init__(self):
        self.TITLE = 'PAGETITLE'
        self.CONTENTS  = 'PAGECONTENT'

if __name__ == '__main__':
    import unittest

    class html_test(unittest.TestCase):

        def test_hFill(self):
            t = 'Hello <#NAME>.  This is a <#THING>. ' * 2

            class x:
                def __init__(self):
                    class y:
                            def __init__(self):
                                self.THING = 'test'
                    self.NAME = 'Joe_<#THING>'
                    self.view = y()
                def replace_tag(self,tagname,options):
                    if tagname in self.view.__dict__:
                        return self.view.__dict__[tagname]
                    else:
                        return '#'+tagname+'#'

            self.assertEquals(hFill(t,x()),'Hello Joe_test.  This is a test. Hello Joe_test.  This is a test. ')

    unittest.main()
